<template>
  <div class="user-photo">
    <img
      :src="imgUrl"
      class="img"
      alt=""
      ref="img"
    >
    <div class="bottom-btn">
      <span
        class="cancel"
        @click="$emit('closePop')"
      >取消</span>
      <span
        class="confirm"
        @click="onConfirm"
      >完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { editUserPhoto } from '@/api/user'
export default {
  name: 'UserPhoto',
  props: {
    imgUrl: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 不能超出图片范围
      dragMode: 'move', // 拖动画布而不是选择框
      aspectRatio: 1, // 选择框的比例
      autoCropArea: 1, // 根据图片大小自动撑满
      cropBoxMovable: false, // 不让选择框移动
      cropBoxResizable: false, // 选择框大小不可变
      background: false, // 没有背景色
      movable: true // 画布可以移动
    })
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        this.$toast.loading({
          message: '保存中...',
          forbidClick: true,
          duration: 0
        })
        try {
          // 接口Content-type是multipart/form-data，所以必须是FormData对象
          const formData = new FormData()
          formData.append('photo', blob) // photo是传过去的数据名
          const { data } = await editUserPhoto(formData)
          // 成功后：  更新视图 关闭弹层 提示成功
          this.$emit('closePop')
          this.$emit('updateUrl', data.data.photo)
          this.$toast.success('修改成功')
        } catch (err) {
          this.$toast('修改失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.user-photo {
  display: flex;
  align-items: center;
  height: 100%;
  background-color: #000;
  .img {
    max-width: 100%;
  }
  .bottom-btn {
    display: flex;
    justify-content: space-between;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    .cancel, .confirm {
      font-size: 40px;
      color: #fff;
    }
  }
}

</style>
